package com.ptl.bp.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ptl.bp.entity.ErrorLogEntity;
import com.ptl.bp.mapper.ErrorLogMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class ErrorReportService extends ServiceImpl<ErrorLogMapper, ErrorLogEntity> {

    private final HttpServletRequest request;

    @Transactional
    public Long reportError(ErrorLogEntity entity) {
        entity.setClientIp(getClientIp());
        this.save(entity);
        return entity.getId();
    }

    public String getClientIp() {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public boolean cleanReportData() {
        LocalDateTime cutoffDate = LocalDateTime.now().minusDays(180);
        return this.lambdaUpdate().ge(ErrorLogEntity::getCreateTime, cutoffDate).remove();
    }
}